﻿using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.KDSServiceHelper;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Text;

namespace WZRJ.ServicePlugIn.BusinessPlugIn
{
    [Kingdee.BOS.Util.HotUpdate]
    [Description("同步报表1")]
    public class ReportOrder : AbstractListPlugIn
    {
        /// <summary>
        /// 菜单点击事件，表单插件同样适用
        /// </summary>
        /// <param name="e"></param>
        ///         [Obsolete]
#pragma warning disable CS0809 // 过时成员重写未过时成员
        [Obsolete]
        public override void BarItemClick(BarItemClickEventArgs e)
        {
#pragma warning restore CS0809 // 过时成员重写未过时成员
            base.BarItemClick(e);
            if (e.BarItemKey == "WZRJ_tbButton")
            {
                this.View.ShowMessage("开始同步报表");
                //string filePathbb = Path.Combine(@"D:\SCWZ_LOG", DateTime.Now.ToString("yyyyMMddHHmmss") + "报表.txt");
                var dy = this.ListView.CanDealWithRows[0].DataRow;
                string jsonbb = Newtonsoft.Json.JsonConvert.SerializeObject(dy);//list转json
                Newtonsoft.Json.Linq.JToken fullToken = Newtonsoft.Json.Linq.JToken.Parse(jsonbb);
                //File.AppendAllText(filePathbb, jsonbb);
                string year = fullToken.SelectToken("DynamicObject.FYEAR")?.ToString();//年
                string period = fullToken.SelectToken("DynamicObject.FPERIOD")?.ToString();//期
                string FRPTID = fullToken.SelectToken("DynamicObject.FRPTID")?.ToString();//更新的id
                string FOrgId = fullToken.SelectToken("DynamicObject.FOrgId_Ref.Number")?.ToString();//所属组织

                var itemdata = KDSServiceHelper.GetMainRptItemData(this.Context, Convert.ToInt32(year), Convert.ToInt32(period));
                string jsonlist = Newtonsoft.Json.JsonConvert.SerializeObject(itemdata);//list转json

                var json = GetJosns(jsonlist, FOrgId);
                var token = GetTokens(); //获取token
                var rev = PostSendDatas(json, token);//发送数据
                string SendSatuas = "C";
                if (rev == "true")
                {
                    SendSatuas = "B";
                    this.View.ShowMessage("报表数据已同步");

                }
                else
                {
                    this.View.ShowErrMessage("报表数据同步失败，失败原因：" + rev + @"");
                }
                //修改同步状态
                DBServiceHelper.ExecuteDataSet(this.Context, "/*dialect*/" + @" 
                update t_KDS_Rpt set F_WZRJ_COMBO1='" + SendSatuas + @"' where FRPTID='" + FRPTID + @"'
                ");

            }
        }

        private static readonly CookieContainer _cookie = new CookieContainer();
        [Obsolete]
        //获取token地址
        public static string GetTokens()
        {

            string adderss = "https://center-krypton.cbit.zhibaocloud.com/oauth/token";
            string client_id = "e37b8f58-149a-496a-bcc8-7c6d114c0cc3";
            string client_secret = "ZDI1NDQxNzEtZmIwNi00NTNiLTkwNGEtNmZmZGJhYmY3Yjdi";
            string scope = "all";
            string resource_id = "1";

            string sendjson = @"" + adderss + @"?grant_type=client_credentials&client_id=" + client_id + @"&client_secret=" + client_secret + @"&scope=" + scope + @"&resource_id=" + resource_id + @"";
            try
            {
                string revjson = "";
                Encoding encoding = Encoding.UTF8;
                byte[] buffer = encoding.GetBytes(sendjson);
                var httpClientHandler = new HttpClientHandler { CookieContainer = _cookie, Proxy = null };
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    var content = new ByteArrayContent(buffer);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded;charset=UTF-8");
                    var result = client.PostAsync(sendjson, content).GetAwaiter().GetResult();
                    revjson = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                }

                //Encoding encoding = Encoding.UTF8;
                //byte[] buffer = encoding.GetBytes(sendjson);//参数格式为Key-Value格式多个参数用&分隔
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sendjson);
                //request.Method = "POST";
                //// request.ContentType = "application/json";
                //request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                //request.ContentLength = buffer.Length;
                //request.AllowWriteStreamBuffering = true;
                //request.GetRequestStream().Write(buffer, 0, buffer.Length);
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                //{
                //    revjson = reader.ReadToEnd();
                //}
                Newtonsoft.Json.Linq.JToken tokenRev = Newtonsoft.Json.Linq.JToken.Parse(revjson);
                var jsondata = tokenRev["access_token"].ToString();
                return jsondata;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [Obsolete]
        //发送数据
        public static string PostSendDatas(string postDataStr, string token)
        {
            try
            {
                string adderss = "https://center-krypton.cbit.zhibaocloud.com/integration/financing/k3cloud/data";
                string revjson = "{}";
                Encoding encoding = Encoding.UTF8;
                byte[] buffer = encoding.GetBytes(postDataStr);
                var httpClientHandler = new HttpClientHandler { CookieContainer = _cookie, Proxy = null };
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                    var content = new ByteArrayContent(buffer);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var result = client.PostAsync(adderss, content).GetAwaiter().GetResult();
                    revjson = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                }
                // 构造请求
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(adderss);
                //byte[] buffer = encoding.GetBytes(postDataStr);//参数格式为Key-Value格式多个参数用&分隔
                //request.Method = "POST";
                //request.ContentType = "application/json";
                //request.Headers.Add("Authorization", "Bearer " + token);
                //request.ContentLength = buffer.Length;
                //request.GetRequestStream().Write(buffer, 0, buffer.Length);
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                //{
                //    revjson = reader.ReadToEnd();
                //}
                return revjson;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        //索引json取对应的组织报表数据
        public static string GetJosns(string json, string FOrgId)
        {
            dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            List<string> jsonlist = new List<string>();
            foreach (var obj in jsonObj)
            {
                if (obj.OrgNumber == FOrgId)
                {
                    jsonlist.Add(obj.ToString());
                }
            }
            string jsonreturn = "[" + string.Join(",", jsonlist) + "]";
            return jsonreturn;
        }
        /// <summary>
        /// 菜单点击后处理事件，表单插件同样适用
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "":
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 对列表数据追加过滤或是排序，推荐通过过滤方案进行处理，如果是特殊的强制过滤，可以在这个位置进行处理
        /// </summary>
        /// <param name="e"></param>
        public override void PrepareFilterParameter(FilterArgs e)
        {
            e.AppendQueryFilter("");
            e.AppendQueryOrderby("");
        }

        /// <summary>
        /// queryservice取数方案，通过业务对象来获取数据，推荐使用
        /// </summary>
        /// <returns></returns>
        public DynamicObjectCollection GetQueryDatas()
        {
            QueryBuilderParemeter paramCatalog = new QueryBuilderParemeter()
            {
                FormId = "",//取数的业务对象
                FilterClauseWihtKey = "",//过滤条件，通过业务对象的字段Key拼装过滤条件
                SelectItems = SelectorItemInfo.CreateItems("", "", ""),//要筛选的字段【业务对象的字段Key】，可以多个，如果要取主键，使用主键名
            };

            DynamicObjectCollection dyDatas = Kingdee.BOS.ServiceHelper.QueryServiceHelper.GetDynamicObjectCollection(this.Context, paramCatalog);
            return dyDatas;
        }
    }
}
